<template>
  <div class="app-container" style="min-height: 88.5vh">
    <!-- 查询操作 -->
    <com-title-item title="查询条件">
      <el-form
        ref="queryForm"
        class="el-form"
        :model="queryParams"
        :inline="true"
        size="mini"
        style="margin-top: 20px"
        label-width="120px"
      >
        <el-form-item label="搬家时间">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :editable="false"
            value-format="timestamp"
            :default-time="['00:00:00', '23:59:59']"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="搬家状态">
          <el-select v-model="queryParams.moveStatus" placeholder="请选择">
            <el-option
              v-for="dict in moveStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-row class="d-flex jc-end">
          <el-button size="mini" type="primary" @click="search">查询</el-button>
          <el-button size="mini" @click="reset">清空查询条件</el-button>
        </el-row>
      </el-form>
    </com-title-item>

    <!-- 查询列表 -->
    <el-table
      style="width: 100%; margin-top: 20px;"
      border
      :data="tableData"
      v-loading="loading"
      :header-cell-style="{ background: '#f0f8ff' }"
      :row-style="{ height: '100px' }"
    >
      <el-table-column
        v-for="item in tableColumn"
        :key="item.id"
        :label="item.label"
        :prop="item.prop"
        :width="item.width"
        :min-width="item.minWidth"
        align="center"
      >
        <template slot-scope="{ row }">
          <template v-if="item.prop">
            <span>{{ row[item.prop] }}</span>
          </template>

          <template v-if="item.id === 'LINK'">
            <el-link v-if="row.link" :href="row.link" target="_blank" :underline="false" type="primary">{{ row.link | linkShort }}</el-link>
          </template>

          <template v-if="item.id === 'STATUS'">
            <i class="el-icon-loading" v-if="row.statusCode === 'P'"></i>
            <span v-else>{{ row.statusLabel }}</span>
            <p class="del-status" v-if="row.delDeleted">(已删除)</p>
          </template>

          <template v-if="item.id === 'STATUS_CAUSE'">
            <span>{{ row.statusFailMsg }}</span>
            <!-- <span>{{ moveControl[row.statusFailCode] ? moveControl[row.statusFailCode].label : "" }}</span> -->
            <!-- <p
              class="btn"
              v-if="row.statusFailCode === '20004'"
              @click="onJumpHouseDetail(row.delegationType, row.delId)"
            >
              <el-button type="text">查看已存在的房源</el-button>
            </p> -->
          </template>

          <template v-if="item.id === 'CONTROL'">
            <!-- <span v-if="row.statusCode === 'S'" @click="onJumpHouseDetail(row.delegationType, row.delId)">
              <el-button type="text">查看房源</el-button>
            </span>
            <span v-if="row.statusFailCode && moveControl[row.statusFailCode]" @click="onMoveFail(row)">
              <el-button type="text">{{ moveControl[row.statusFailCode].button }}</el-button>
            </span> -->
            <span v-for="(option, i) in row.options" :key="i" style="margin: 0 6px">
              <el-button type="text" :disabled="row.delDeleted && option.label.indexOf('查看') !== -1" @click="handleOption(option.button, row)">{{ option.label }}</el-button>
            </span>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-row type="flex" justify="end">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="loadLogList"
      />
    </el-row>
  </div>
</template>

<script>
import { HOUSE_MOVE, HOUSE_PUSH, VR_COMPOUND_ADD } from "@/config/menuId";
import { menuHandler } from "@/handler/menuHandler";
import { taskList, taskListByIds, importPickOutHouseResources, movingHouse, getMemberPower } from "@/api/user";
import { timeStampToDate } from "@/utils/utilsNew";
import comTitleItem from "../house/com/com-title-item";
import pagination from "@/components/Pagination";
import { mapGetters } from "vuex";
import { startOfDay, endOfDay, format } from 'date-fns';

export default {
  components: {
    comTitleItem,
    pagination,
  },
  computed: {
    ...mapGetters(["sessionUser"]),
  },
  data() {
    return {
      loading: false,
      total: 0,
      queryParams: {
        page: 1,
        pageSize: 10,
        dateRange: [],
        moveStatus: "A",
      },
      tableData: [],
      tableColumn: [
        { id: "LINK", label: "搬家链接", width: "0" },
        { id: "TIME_START", label: "开始时间", prop: "startTime", width: "180" },
        { id: "TIME_END", label: "结束时间", prop: "endTime", width: "180" },
        { id: "STATUS", label: "搬家状态", prop: "status", width: "100" },
        { id: "STATUS_CAUSE", label: "失败原因", width: "200" },
        { id: "CONTROL", label: "操作", width: "180" },
      ],
      moveStatusOptions: [
        { dictValue: "A", dictLabel: "全部" },
        { dictValue: "S", dictLabel: "搬家成功" },
        { dictValue: "P", dictLabel: "搬家中" },
        { dictValue: "F", dictLabel: "搬家失败" },
      ],
      moveControl: {
        "20002": { label: "网络超时", button: "重试" },
        "20003": { label: "目前不支持该网站搬家", button: "" },
        "20004": { label: "该房源已进行过搬家", button: "再搬一次" },
      },
    };
  },
  mounted() {
    this.initDefaultFilterTime()
    this.search();
  },
  beforeDestroy() {
    let t = this;
    clearInterval(t.timer);
    t.timer = null;
  },
  filters: {
    linkShort(v) {
      return v.slice(0, 50) + '...'
    },
  },
  methods: {
    initDefaultFilterTime() {
      this.queryParams.dateRange = [startOfDay(new Date()).getTime(), endOfDay(new Date()).getTime()]
    },
    async loadLogList() {
      let t = this;
      try {
        t.loading = true;
        let res = await taskList({
          startTime: t.queryParams.dateRange ? t.queryParams.dateRange[0] : null,
          endTime: t.queryParams.dateRange ? t.queryParams.dateRange[1] : null,
          pageNum: t.queryParams.page,
          pageSize: t.queryParams.pageSize,
          state: t.queryParams.moveStatus || null,
        });
        if (res && res.isSuccess && res.content) {
          let result = res.content || {};
          t.total = result.total || 0;
          let list = result.list.map((item, index) => {
            return t.formatHouseItem(item);
          });
          t.tableData = list;
        }
      } catch (error) {
      } finally {
        t.checkStatusChange();
        t.loading = false;
      }
    },
    reset() {
      this.queryParams.dateRange = [];
      this.queryParams.page = 1;
      this.queryParams.moveStatus = "A";
    },
    search() {
      this.queryParams.page = 1;
      this.loadLogList();
    },

    // 所有操作
    handleOption(button, data = {}) {
      let t = this;
      switch (button) {
        case "view":
          this.onJumpHouseDetail({
            delegationType: data.delegationType,
            delId: data.delId,
            delDeleted: data.delDeleted,
          });
          break;
        case "repeat":
          this.$confirm("是否确认重新给搬家?", "提示", {
            confirmButtonText: "是",
            cancelButtonText: "否",
          })
            .then(() => {
              t.checkVrAuth()
                .then(() => {
                  t.moveHouse({ url: data.link, isVr: data.isVr, isRepeat: true });
                })
                .catch(() => {});
            })
            .catch(() => {});
          break;
          
        case "retry":
          t.checkVrAuth()
            .then(() => {
              t.moveHouse({ url: data.link, isVr: data.isVr, isRepeat: true });
            })
            .catch(() => {});
          break;
      }
    },
    onJumpHouseDetail({ delegationType, delId = "", delDeleted }) {
      if (delDeleted) return;
      this.$router.push({
        name: delegationType === "SALES" ? "modifyHouseNew" : "modifyHouse",
        params: { houDelId: delId },
      });
    },
    checkStatusChange() {
      let t = this;
      clearInterval(t.timer);
      t.timer = null;
      let filter = t.tableData.filter((item) => {
        return item.statusCode === "P";
      });
      let idList = filter.map((item) => {
        return item.moveId;
      });
      if (idList && idList.length) {
        t.timer = setInterval(async () => {
          let res = await taskListByIds(idList);
          if (res && res.isSuccess && res.content && res.content.length) {
            let flag = false;
            res.content.forEach((item) => {
              if (item.pickOutStatus === "P") {
                flag = true;
              }
              if (item.pickOutStatus === "S" || item.pickOutStatus === "F") {
                t.tableData.forEach((ite, idx) => {
                  if (ite.moveId === item.id) {
                    t.tableData.splice(idx, 1, t.formatHouseItem(item));
                  }
                });
              }
            });
            if (!flag) {
              clearInterval(t.timer);
              t.timer = null;
            }
          }
        }, 10000);
      } else {
        clearInterval(t.timer);
        t.timer = null;
      }
    },
    formatHouseItem(item) {
      if (item) {
        let status = "";
        switch (item.pickOutStatus) {
          case "S":
            status = "搬家成功";
            break;
          case "F":
            status = "搬家失败";
            break;
          case "P":
            status = "搬家中";
            break;
        }
        return {
          moveId: item.id || "",
          delId: item.delId || "",
          link: item.url || "",
          startTime: item.createTime ? timeStampToDate(item.createTime) : "",
          endTime: item.updateTime ? timeStampToDate(item.updateTime) : "",
          statusLabel: status,
          statusCode: item.pickOutStatus || "",
          statusFailMsg: item.errorMessage || "",
          statusFailCode: item.errorCode || "",
          delegationType: item.delegationType || "",
          isVr: item.vrFlag || false,
          options: item.options || [],
          delDeleted: item.delDeleted || false,
        };
      } else {
        return item;
      }
    },
    checkVrAuth() {
      return new Promise((resolve, reject) => {
        menuHandler
          .call(this, HOUSE_MOVE)
          .then(() => {
            resolve();
          })
          .catch((error) => {
            reject();
          });
      });
    },
    moveHouse({ url, isVr, isRepeat }) {
      return new Promise((resolve, reject) => {
        movingHouse([
          {
            url: url || "",
            vrFlag: isVr,
            skipRepeat: isRepeat ? "1" : "0",
          },
        ]).then((data) => {
          if (data && data.isSuccess) {
            this.search();
            resolve();

            getMemberPower({
              menuId: HOUSE_MOVE,
              agentId: this.sessionUser.id,
            });
          } else {
            this.$message.error("非常抱歉：搬家失败。");
            reject();
          }
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background: #f6f6f6;
}

.pagination-container {
  background: none;
  padding: 0;
}

.btn {
  margin: 0;
}

.del-status{
  margin: 0;
}
</style>
